<?php
	/**
	 * Transform PHP arrays into ini files.
	 * @author IMP
	 */
	
	class IniTransformer extends ArrayIterator {
		public function __construct($a = array()){
			parent::__construct(array());
			
			foreach($a as $k => $v){
				if(is_array($v)){
					$this->addSection(new IniSection($k, $v));
				}else{
					$this[$k] = $v;
				}
			}
		}
		
		public function addSection($section){
			if(!($section instanceof IniSection)) $section = new IniSection($section);
			$this[$section->getName()] = $section;
		}
		
		public function getSections(){
			$secs = array();
			foreach($this as $d){
				if($d instanceof IniSection) $secs[$d->getName()] = $d;
			}
			
			return $secs;
		}
		
		public function get($name, $default = null){
			if(isset($this[$name])){
				return $this[$name];
			}else{
				return $default;
			}
		}
		
		public function emit(){
			$rawLines = array();
			$sectionLines = array();
			
			foreach($this as $k => $v){
				if($v instanceof IniSection){
					$sectionLines[] = $v->emit();
				}else{
					$rawLines[] = self::generateAllocationLine($k, $v);
				}
			}
			
			return implode(PHP_EOL, $rawLines) . (count($rawLines) > 0 ? PHP_EOL : '') . implode(PHP_EOL, $sectionLines);
		}
		
		public function save(File $output){
			$output->write($this->emit());
		}
		
		public static function generateAllocationLine($key, $value){
			if(is_array($value)){
				$emit = array();
				foreach($value as $k => $v){
					if(!is_string($k)){
						$emit[] = $key . '[]=' . $v;
					}else{
						$emit[] = $key . '[' . $k . ']=' . $v;
					}
				}
				
				return implode(PHP_EOL, $emit);
			}else{
				return $key . '=' . $value;
			}
		}
		
		
	}
?>